package com.ch.engine.gc;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class GcTriggerController {

    private final List<byte[]> memoryHog = new ArrayList<>();

    @GetMapping("/trigger-gc")
    public String triggerGc() {
        // 分配大块内存，快速占满堆，促使GC触发
        for (int i = 0; i < 100; i++) {
            // 1MB
            byte[] block = new byte[1024 * 1024];
            memoryHog.add(block);
        }
        // 手动建议JVM做GC，虽然不保证立即执行
        System.gc();

        return "Triggered GC, allocated ~100MB memory";
    }

    @GetMapping("/clear")
    public String clearMemory() {
        memoryHog.clear();
        System.gc();
        return "Cleared memory and triggered GC";
    }
}
